package com.itheima.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.dtos.LoginAuthDto;
import com.itheima.mapper.UserMapper;
import com.itheima.pojos.User;
import com.itheima.service.UserService;
import com.itheima.vos.LoginAuthVO;
import com.itheima.vos.UserBaseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangjiexin
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public LoginAuthVO login(LoginAuthDto dto) {
        //1．入参判断
        //判断dto是否为空
        if (dto == null) {
            throw new RuntimeException("入参不能为空");
        }

        // 1.2判断手机号和验证码是否为空
        String phone = dto.getPhone();
        String password = dto.getPassword();

        // 2．为空（游客)
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)) {
            User tourist=new User();
            tourist.setId(0L);
          return getLoginAuthVO(tourist);
        }


        //3不为空（正常登录)
        // 3.1 手机号格式校验
        //糊涂工具的这个方法可以用来检查手机号码格式
        boolean mobile = Validator.isMobile(phone);
        if (!mobile) {
            throw new RuntimeException("手机号码格式错误");
        }
        // 3.2到数据库查询手机号是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userMapper.selectOne(wrapper);

        //3.4手机号不存在
        if (user == null) {
            //3.4.1创建手机号
            //3.4.2组装用户信息->生成token
            User newuser = new User();
            newuser.setName("新用户:" + System.currentTimeMillis());
            newuser.setPhone(phone);
            newuser.setStatus(false);
            newuser.setSex(false);
            newuser.setIdentityAuthentication(false);
            newuser.setId(IdUtil.getSnowflakeNextId());
            newuser.setFlag(0);
            newuser.setImage("");
            newuser.setCreatedTime(new Date());
            int insert = userMapper.insert(newuser);
            if (insert != 1) {
                throw new RuntimeException("创建用户异常~!");
            }

            //3.4.3返回组装后的信息
            return getLoginAuthVO(newuser);
        }

        // 3.3 手机号存在
        //3.3.1组装用户信息->生成token
        //3.3.2返回组装后的信息
        //如果能查到这个用户信息，直接调用方法生成token返回上去就可以了
        return getLoginAuthVO(user);
    }
    public LoginAuthVO getLoginAuthVO(User user){
        // 2.1组装用户信息（用户id: 0)->生成token
        //组装一个map
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", user.getId());
        //生成token
        String token = JWTUtil.createToken(null, payload, "heimaleadnews".getBytes());

        LoginAuthVO vo = new LoginAuthVO();
        vo.setUser(user);
        vo.setToken(token);
        // 返回组装后的信息
        return vo;
    }
}
